package com.chengyu.core.service.walk.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.TypeReference;
import com.alibaba.fastjson.JSONObject;
import com.chengyu.core.domain.CommonConstant;
import com.chengyu.core.domain.enums.TrendsEnums;
import com.chengyu.core.domain.form.TrendsForm;
import com.chengyu.core.domain.result.WalkTrendsCommentResult;
import com.chengyu.core.domain.result.WalkTrendsDownloadNumResult;
import com.chengyu.core.domain.result.WalkTrendsResult;
import com.chengyu.core.entity.CommonPage;
import com.chengyu.core.entity.CommonResult;
import com.chengyu.core.exception.ServiceException;
import com.chengyu.core.mapper.*;
import com.chengyu.core.model.*;
import com.chengyu.core.service.goods.GoodsService;
import com.chengyu.core.service.walk.WalkMemberCollectService;
import com.chengyu.core.service.walk.WalkTrendsDownloadNumService;
import com.chengyu.core.service.walk.WalkTrendsDownloadService;
import com.chengyu.core.service.walk.WalkTrendsService;
import com.chengyu.core.utils.NumberUtils;
import com.chengyu.core.utils.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.YearMonth;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class WalkTrendsDownloadNumServiceImpl implements WalkTrendsDownloadNumService {

    @Autowired
    private WalkTrendsDownloadNumMapper walkTrendsDownloadNumMapper;
    @Autowired
    private PmsGoodsMapper pmsGoodsMapper;
    @Autowired
    private UmsShopMapper umsShopMapper;
    @Autowired
    private WalkTrendsGoodsMapper walkTrendsGoodsMapper;
    @Autowired
    private UmsShopConfigMapper umsShopConfigMapper;
    @Autowired
    private UmsMemberThirdAccountMapper umsMemberThirdAccountMapper;

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void addDownloadNum(Integer trendsId, Integer type, WalkTrendsDownloadNum walkTrendsDownload, WalkMember walkMember, UmsMember umsMember) throws ServiceException, ParseException {
        //根据动态id查看他的对应的商品
        if (trendsId != null) {
            WalkTrendsGoodsExample exampleGoods = new WalkTrendsGoodsExample();
            WalkTrendsGoodsExample.Criteria criteriaGoods = exampleGoods.createCriteria();
            criteriaGoods.andTrendsIdEqualTo(trendsId);
            List<WalkTrendsGoods> walkTrendsGoodsList = walkTrendsGoodsMapper.selectByExample(exampleGoods);
            Integer goodsId = walkTrendsGoodsList.get(0).getGoodsId();
            walkTrendsDownload.setGoodsId(goodsId);
        }


        //先查看是否已经有未使用的并且是在待审核或通过的
        WalkTrendsDownloadNumExample example = new WalkTrendsDownloadNumExample();
        WalkTrendsDownloadNumExample.Criteria criteria = example.createCriteria();
        criteria.andDownloadWalkMemberIdEqualTo(walkMember.getId());

        LocalDate now = LocalDate.now();  // 获取当前日期
        LocalDate startOfMonth = now.withDayOfMonth(1);  // 设置为该月的第一天
        System.out.println("该月的开始时间：" + startOfMonth);
        YearMonth yearMonth = YearMonth.now();  // 获取当前年份和月份
        LocalDate endOfMonth = yearMonth.atEndOfMonth();  // 获取该月的最后一天
        System.out.println("该月的结束时间：" + endOfMonth);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        criteria.andAddTimeBetween(formatter.parse(startOfMonth.toString() + " 00:00:00"), formatter.parse(endOfMonth.toString() + " 00:00:00"));
        List checkStatus = new ArrayList();
        checkStatus.add(CommonConstant.NO_INT);//待审核的
        checkStatus.add(CommonConstant.YES_INT);//审核通过的
        criteria.andStatusIn(checkStatus);
        criteria.andSourceEqualTo(2);//来源为申请
        criteria.andTypeEqualTo(type);
        List<WalkTrendsDownloadNum> walkTrendsDownloadNumList = walkTrendsDownloadNumMapper.selectByExample(example);

        UmsShopConfigExample exampleShopConfig = new UmsShopConfigExample();
        UmsShopConfigExample.Criteria criteriaShopConfig = exampleShopConfig.createCriteria();
        criteriaShopConfig.andShopIdEqualTo(umsMember.getShopId());
        List<UmsShopConfig> umsShopConfigs = umsShopConfigMapper.selectByExample(exampleShopConfig);
        UmsShopConfig umsShopConfig = umsShopConfigs.get(0);

        if (type == 1) {
            if (walkTrendsDownloadNumList.size() >= umsShopConfig.getToApplyDownloadTimeVideo()) {
                throw new ServiceException("用户每个月只能最多申请" + umsShopConfig.getToApplyDownloadTimeVideo() + "次");
            }
        } else if (type == 3) {
            if (walkTrendsDownloadNumList.size() >= umsShopConfig.getToApplyDownloadTimeImg()) {
                throw new ServiceException("用户每个月只能最多申请" + umsShopConfig.getToApplyDownloadTimeImg() + "次");
            }
        }

        //查询出每个媒体账号的数量
        UmsMemberThirdAccountExample exampleThird = new UmsMemberThirdAccountExample();
        UmsMemberThirdAccountExample.Criteria criteriaThird = exampleThird.createCriteria();
        criteriaThird.andMemberIdEqualTo(umsMember.getId());
        List<UmsMemberThirdAccount> umsMemberThirdAccounts = umsMemberThirdAccountMapper.selectByExample(exampleThird);

        int total = umsMemberThirdAccounts.size();
        if (total == 0) {
            throw new ServiceException("必须要绑定了第三方媒体账号才能申请");
        }
        //判断当前是否还有可用次数
        WalkTrendsDownloadNumExample exampleDownloadNum = new WalkTrendsDownloadNumExample();
        WalkTrendsDownloadNumExample.Criteria criteriaDownloadNum = exampleDownloadNum.createCriteria();
        criteriaDownloadNum.andDownloadWalkMemberIdEqualTo(walkMember.getId());
        List<WalkTrendsDownloadNum> walkTrendsDownloadNums = walkTrendsDownloadNumMapper.selectByExample(exampleDownloadNum);
        Integer totalUseTimes = 0;
        for (WalkTrendsDownloadNum walkTrendsDownloadNum : walkTrendsDownloadNums) {
            totalUseTimes = totalUseTimes + walkTrendsDownloadNum.getUseNum();
        }
        if (totalUseTimes > 0) {
            //如果还有可用次数
            throw new ServiceException("您还存在未使用的次数，请使用后申请");
        }

        walkTrendsDownload.setDownloadWalkMemberId(walkMember.getId());
        walkTrendsDownload.setDownloadWalkMemberName(walkMember.getNickname());
        walkTrendsDownload.setDownloadWalkMemberHeadImg(walkMember.getMemberHeadImg());
        walkTrendsDownload.setAddBy(walkMember.getMemberName());
        walkTrendsDownload.setAddTime(DateUtil.date());
        walkTrendsDownload.setNum(walkTrendsDownload.getNum());
        walkTrendsDownload.setStatus(CommonConstant.NO_INT);
        walkTrendsDownload.setShopId(umsMember.getShopId());
        walkTrendsDownload.setSource(2);
        walkTrendsDownload.setUseNum(walkTrendsDownload.getNum());
        walkTrendsDownload.setType(type);
        walkTrendsDownloadNumMapper.insertSelective(walkTrendsDownload);
    }

    @Override
    public CommonPage<WalkTrendsDownloadNum> listDownloadNum(Integer source, Date dateFrom, Date dateTo, Integer shopId, Integer status, Integer type, Integer walkMemberId, Integer page, Integer pageSize, Integer deleteStatus) throws ServiceException {
        PageHelper.startPage(page, pageSize);
        WalkTrendsDownloadNumExample example = new WalkTrendsDownloadNumExample();
        example.setOrderByClause("add_time desc");
        WalkTrendsDownloadNumExample.Criteria criteria = example.createCriteria();

        if (shopId != null) {
            criteria.andShopIdEqualTo(shopId);
        }
        if (status != null) {
            criteria.andStatusEqualTo(status);
        }
        if (type != null) {
            criteria.andTypeEqualTo(type);
        }
        if (walkMemberId != null) {
            criteria.andDownloadWalkMemberIdEqualTo(walkMemberId);
        }
        if (type != null) {
            criteria.andTypeEqualTo(type);
        }
        if (dateFrom != null && dateTo != null) {
            criteria.andAddTimeBetween(dateFrom, dateTo);
        }
        if (source != null) {
            criteria.andSourceEqualTo(source);
        }
        if (deleteStatus != null) {
            criteria.andStatusNotEqualTo(4);
        }

        List<WalkTrendsDownloadNum> walkTrendsDownloadNumList = walkTrendsDownloadNumMapper.selectByExample(example);
        List<WalkTrendsDownloadNumResult> walkTrendsDownloadNumResultArrayList = new ArrayList<>();
        for (WalkTrendsDownloadNum walkTrendsDownloadNum : walkTrendsDownloadNumList) {
            WalkTrendsDownloadNumResult walkTrendsDownloadNumResult = new WalkTrendsDownloadNumResult();
            PmsGoods pmsGoods = pmsGoodsMapper.selectByPrimaryKey(walkTrendsDownloadNum.getGoodsId());
            UmsShop umsShop = umsShopMapper.selectByPrimaryKey(walkTrendsDownloadNum.getShopId());
            walkTrendsDownloadNumResult.setPmsGoods(pmsGoods);
            walkTrendsDownloadNumResult.setUmsShop(umsShop);
            walkTrendsDownloadNumResult.setWalkTrendsDownloadNum(walkTrendsDownloadNum);
            walkTrendsDownloadNumResultArrayList.add(walkTrendsDownloadNumResult);
        }


        PageInfo pageInfo = new PageInfo<>(walkTrendsDownloadNumList);
        pageInfo.setList(walkTrendsDownloadNumResultArrayList);
        return CommonPage.restPage(pageInfo);
    }

    @Override
    public CommonPage<WalkTrendsDownloadNum> listDownloadNumToUse(Integer goodsId, Integer type, Integer walkMemberId, Integer page, Integer pageSize) throws ServiceException {
        PageHelper.startPage(page, pageSize);
        WalkTrendsDownloadNumExample example = new WalkTrendsDownloadNumExample();
        example.setOrderByClause("add_time desc");
        WalkTrendsDownloadNumExample.Criteria criteria = example.createCriteria();

        //查询出一下条件的记录
        //1，审核通过的  2，可使用次数不能等于0   3，商品没有指定，或指定了但是等于传入商品的
        criteria.andTypeEqualTo(type).andStatusEqualTo(CommonConstant.YES_INT).andUseNumNotEqualTo(0).andGoodsIdIsNull().andDownloadWalkMemberIdEqualTo(walkMemberId);
        if (goodsId != null) {
            example.or().andTypeEqualTo(type).andStatusEqualTo(CommonConstant.YES_INT).andUseNumNotEqualTo(0).andGoodsIdEqualTo(goodsId).andDownloadWalkMemberIdEqualTo(walkMemberId);
        }
        List<WalkTrendsDownloadNum> walkTrendsDownloadNumList = walkTrendsDownloadNumMapper.selectByExample(example);
        List<WalkTrendsDownloadNumResult> walkTrendsDownloadNumResultArrayList = new ArrayList<>();
        for (WalkTrendsDownloadNum walkTrendsDownloadNum : walkTrendsDownloadNumList) {
            WalkTrendsDownloadNumResult walkTrendsDownloadNumResult = new WalkTrendsDownloadNumResult();
            PmsGoods pmsGoods = pmsGoodsMapper.selectByPrimaryKey(walkTrendsDownloadNum.getGoodsId());
            walkTrendsDownloadNumResult.setPmsGoods(pmsGoods);
            walkTrendsDownloadNumResult.setWalkTrendsDownloadNum(walkTrendsDownloadNum);
            walkTrendsDownloadNumResultArrayList.add(walkTrendsDownloadNumResult);
        }


        PageInfo pageInfo = new PageInfo<>(walkTrendsDownloadNumList);
        pageInfo.setList(walkTrendsDownloadNumResultArrayList);
        return CommonPage.restPage(pageInfo);
    }


    @Override
    public void editDownloadNum(WalkTrendsDownloadNum walkTrendsDownloadNum) throws ServiceException {
        walkTrendsDownloadNumMapper.updateByPrimaryKeySelective(walkTrendsDownloadNum);
    }

    @Override
    public void delDownloadNum(Integer id) throws ServiceException {
        if (id == null) {
            throw new ServiceException("删除id不能为空");
        }
        WalkTrendsDownloadNum walkTrendsDownloadNum = walkTrendsDownloadNumMapper.selectByPrimaryKey(id);
        if (walkTrendsDownloadNum.getStatus() == 1) {
            throw new ServiceException("此条申请已经申请通过并未使用，无法删除");
        }
        walkTrendsDownloadNumMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void delDownloadNumByMember(Integer id) throws ServiceException {
        WalkTrendsDownloadNum walkTrendsDownloadNum = new WalkTrendsDownloadNum();
        walkTrendsDownloadNum.setStatus(4);
        walkTrendsDownloadNum.setId(id);
        walkTrendsDownloadNumMapper.updateByPrimaryKeySelective(walkTrendsDownloadNum);
    }


}